import React, {
	Component
}
from 'react';

import {
	render,
	Timer
}
from 'react-dom';

import {
	Spin, Row, Col, Form, Input, Button, Icon, Table, Badge, Timeline, message, Modal, Radio
}
from 'antd';

import {
	IndexBanner
}
from './index-banner';

import {
	Link
}
from 'react-router';

var EP = {
	fns: {},
	on: function(name, ctx, fn) {
		if (!this.fns[name]) {
			this.fns[name] = [];
		}
		fn.ctx = ctx;
		this.fns[name].push(fn);
	},
	emit: function(name, data) {
		var fns = this.fns[name];

		for (var i = 0; i < fns.length; i++) {
			fns[i].call(fns[i].ctx, data);
		}
	}
};

var generateJson = function (res){
		
	var json = {};
	
	if( res.length < 1 ){
		return '';
	}
	
	for(var i=0;i<res.length;i++){
		var keyName = res[i]._serverData['hotel'];
		
		if( !json[ ''+ keyName +'' ] ){
			json[ ''+ keyName +'' ] = {};
		}
		
		var disheskeyName = res[i]._serverData['dishes'];
		if( typeof disheskeyName != 'undefined'){
			
			if( !json[ ''+ keyName +'' ][''+ disheskeyName +''] ){
				json[ ''+ keyName +'' ][''+ disheskeyName +''] = 1;
			}else{
				json[ ''+ keyName +'' ][''+ disheskeyName +''] = json[ ''+ keyName +'' ][''+ disheskeyName +''] + 1;
			}
		}		
	}

	return json;
}

var __Array = [];

const stopSeconds = (18 * 60 + 59) * 60 + 59;

function getDay() {
	var today = new Date();
	var dayTag = "" + today.getFullYear() + today.getMonth() + today.getDate();
	return dayTag;
}

class MenuBtn extends Component {
	constructor(props) {
		super(props);
		this.state = {};
	}
	handleClick() {
		EP.emit('addDish', this.props.record.attributes);
	}
	render() {
		return (
			<span className="dish-add" onClick={this.handleClick.bind(this)}>
				<Icon type="plus-circle-o" />
			</span>
		)
	}
}

class FoodItemAdd extends Component {
	constructor(props) {
		super(props);
		this.state = {};
	}
	handleClick() {
		EP.emit('addDish', this.props.item);
	}
	render() {
		return (
			<span className="cart-btn" onClick={this.handleClick.bind(this)}>
				<Icon type="plus" />
			</span>
		)
	}
}
class MenuList extends Component {
	constructor(props) {
		super(props);

		var seconds = this.props.seconds;

		this.state = {
			viewmode: 'img',
			key: 'all',
			store: 'fpp',
			loaded: false,
			data: [],
			over: false//seconds <= 0 ? true : false
		};

		var keymap = {
			'all': {
				key: 'all',
				text: '全部'
			},
			rice: {
				key: '饭',
				text: '盖饭'
			},
			noodle: {
				key: '面',
				text: '面条'
			},
			zha: {
				key: '炸',
				text: '炸鸡没啤酒'
			},
			shala: {
				key: '沙拉',
				text: '沙拉'
			},
			fruit: {
				key: '水果',
				text: '水果'
			},
		};

		this.state.keyword = keymap;

		if (this.state.over) return;

		this.loadMenu();
	}
	loadMenu() {
		var MenuObj = Bmob.Object.extend("menu");
		var query = new Bmob.Query(MenuObj);
		var context = this;

		query.limit(1000);
		query.find({
			success: function(results) {
				context.setState({
					loaded: true,
					data: results
				});
			},
			error: function(error) {
				alert("查询失败: " + error.code + " " + error.message);
			}
		});
	}
	filter(ev) {
		ev.preventDefault();

		let key = ev.target.getAttribute('data-key');

		this.setState({
			key: key
		})
	}
	changeView(view, ev) {
		ev.preventDefault();

		this.setState({
			viewmode: view
		});
	}
	changeShop(e){
		console.log('shop change', e.target.value);
		this.setState({
			store: e.target.value
		})
	}
	render() {

		if (this.state.over) {
			return (
				<div style={{color:'#5C6B77', textAlign: 'center', padding: '6em 0', fontSize: '16px'}}>
					<span style={{fontSize: '70px', verticalAlign: 'middle', display: 'block', marginBottom: '4px'}}><Icon type="frown-circle" /></span>
					订餐结束！明天再来吧
				</div>
			)
		}

		if (!this.state.loaded) {
			return (
				<div style={{padding: '6em 0 6em',textAlign: 'center'}}>
					<Spin />
				</div>
			);
		} else {
			var key = this.state.key,
				keyword = this.state.keyword,
				viewmode = this.state.viewmode,
				data = this.state.data,
				view;

			const rowHide = function(record) {
				return key in keyword && key !== 'all' && record.attributes.name.indexOf(keyword[key].key) == -1;
			}
			const columns = [{
				title: '名称',
				dataIndex: 'name',
				key: 'name',
				render: function(text, record) {
					if (rowHide(record)) {
						return {
							children: <span></span>,
							props: {
								rowSpan: 0
							}
						}
					}
					return (
						<span>
						{record.attributes.name}
						</span>
					)
				}
			}, {
				title: '价格/元',
				dataIndex: 'price',
				key: 'price',
				render: function(text, record) {
					if (rowHide(record)) {
						return {
							children: <span></span>,
							props: {
								rowSpan: 0
							}
						}
					}
					return (
						<span>
						{record.attributes.price}
						</span>
					)
				}
			}, {
				title: '操作',
				dataIndex: 'opt',
				key: 'opt',
				render: function(text, record) {
					if (rowHide(record)) {
						return {
							children: <span></span>,
							props: {
								rowSpan: 0
							}
						}
					}

					return (
						<MenuBtn record={record}/>
					)
				}
			}];

			let rowKey = function(record) {
				return record.cid
			}

			data = data.filter((item)=>{
				var obj = item.attributes;

				return obj.store == this.state.store;
			})

			if (viewmode == 'table') {
				view = <Table rowKey={rowKey} columns={columns} dataSource={data} pagination={false}/>;
			} else if (viewmode == 'img') {
				let items = [];

				data.forEach(function(record, i){
					var data = record.attributes;

					if(key === 'all' || !key){
						items.push(<FoodItem item={data} key={data.key}/>)
					}else if(key in keyword && data.name.indexOf(keyword[key].key) !== -1){
						items.push(<FoodItem item={data} key={data.key}/>)
					}
				})


				if(!items.length){
					items = <div className="img-holder" data-empty-word="(┬＿┬)木有"></div>;
				}

				view = <div>
						<ul className="foods">
						{
							items
						}
						</ul>
					</div>
			}

			let filterItems = [];
			for(var k in keyword){
				let word = keyword[k].text;
				let item = <a href="javascript" className={this.state.key == k ? 'on':''} data-key={k} onClick={this.filter.bind(this)}>{word}</a>;
				filterItems.push(item);
			}

			return (

				<div className="dishes-container">
					<h2>拉轰菜单</h2>
					<div className="shop-filter-bar">
						<Radio.Group onChange={this.changeShop.bind(this)} defaultValue="fpp">
							<Radio value="fpp">粉婆婆</Radio>
							<Radio value="mn">木南家</Radio>
						</Radio.Group>
					</div>
					
					<div className="foods-view-ctrl">
						<span>
							<a href="javascript:;" 
								className={this.state.viewmode == 'img' ? 'on':''}
								onClick={this.changeView.bind(this, 'img')}>
								<Icon type="picture"></Icon>
							</a>
							<a href="javascript:;" 
								className={this.state.viewmode == 'table' ? 'on':''}
								onClick={this.changeView.bind(this, 'table')}>
								<Icon type="bars"></Icon>
							</a>
						</span>	
					</div>
					<div className="foods-filter-bar" data-key={key}>
					{
						filterItems
					}
					</div>
					{
						view
					}
				</div>
			)
		}
	}
}

class Cart extends Component {
	constructor(props) {
		super(props);
		this.state = {
			money: 0,
			total: 0,
			dishes: []
		};



		EP.on('addDish', this, function(dish) {
			var dishes = this.add(dish);

			this.afterAdd(dish, dishes);
		});

		EP.on('reduceDish', this, function(dish) {
			dishes = this.reduce(dish);

			this.afterReduce(dish, dishes);
		})
	}
	afterAdd(dish, dishes) {
		var m = this.state.money,
			t = this.state.total;

		t++;

		m += dish.price;

		this.setState({
			money: m,
			total: t,
			dishes: dishes
		})
	}
	afterReduce(dish, dishes) {
		var m = this.state.money,
			t = this.state.total;

		t--;

		m -= dish.price;

		this.setState({
			money: m,
			total: t,
			dishes: dishes
		})
	}
	add(dish) {
		var old = this.state.dishes,
			exist = false;

		for (var i = 0; i < old.length; i++) {
			var item = old[i];
			if (item.key === dish.key) {
				item.total += 1;
				exist = true;
				break;
			}
		}
		if (!exist) {
			old.push({
				key: dish.key,
				name: dish.name,
				price: dish.price,
				store: dish.store,
				total: 1
			})
		}

		return old;
	}
	reduce(record, ev) {
		var old = this.state.dishes,
			exist = false;

		for (var i = 0; i < old.length; i++) {
			var item = old[i];
			if (item.key === record.key) {
				item.total -= 1;

				if (item.total == 0) {
					old.splice(i, 1);
				}
				/*item.name += ',' + item.name;*/
				break;
			}
		}

		this.afterReduce(record, old);
	}
	getNames() {
		
		var arr = this.state.dishes,
			dish = null,
			names = [];

		for (var i = 0; i < arr.length; i++) {
			var total = arr[i].total;
			dish = arr[i];

			do {
				names = names.concat(dish.store + '-' + dish.name);
				total--;
			} while (total > 0)
		}

		return names;
	}
	getJsonNames() {
		
		var arr = this.state.dishes,
			dish = null,
			Json = {};
		__Array = [];

		for (var i = 0; i < arr.length; i++) {
			var total = arr[i].total;
			dish = arr[i];
			
			do {
				var num = 1;
				
				if( typeof Json[''+ dish.store +''] == 'undefined' ){
					Json[''+ dish.store +''] = {}
				}
				
				if( typeof Json[''+ dish.store +''][''+ dish.name +''] != 'undefined'){
					num++;
				}else{
					Json[''+ dish.store +''][''+ dish.name +''] = {};
				}
				
				Json[''+ dish.store +''][''+ dish.name +''] = num;
				
				__Array[i] = {};
				__Array[i].store = dish.name;
				__Array[i].hotel = dish.store;
				
				total--;
			} while (total > 0)
		}

		return Json;
	}
	getDishKeys(){
		var arr = this.state.dishes,
			dish = null,
			keys = [];

		for (var i = 0; i < arr.length; i++) {
			var total = arr[i].total;
			dish = arr[i];

			do {
				keys.push(dish.key);
				total--;
			} while (total > 0)
		}

		return keys;
	}
	getUserName() {
		var name = this.refs.inputname.value;

		return name;
	}
	clear() {
		this.setState({
			money: 0,
			total: 0,
			dishes: []
		})
	}
	
	getDay() {
		var today = new Date();
		var dayTag = "" + today.getFullYear() + today.getMonth() + today.getDate();
		return dayTag;
	}
	
	OrderNum(callback) {
		var OrderObj = Bmob.Object.extend("order");
		var query = new Bmob.Query(OrderObj);
		query.limit(1000);
		query.equalTo("bookday", getDay());
		query.find({
			success: function(results) {
				callback( generateJson(results) )
			},
			error: function(error) {
				alert("查询失败: " + error.code + " " + error.message);
			}
		});
	}
	
	_submitOrder() {
		
		const cart = this;
		var name = this.getUserName();
		this.state.submiting = true;

		var Books = Bmob.Object.extend("books");
		var books = new Books();

		books.set("username", name);
		books.set("confirmkey", commonFingerPrint.get());
		books.set("dishes", this.getNames());
		books.set("money", this.state.money);
		books.set("bookday", getDay());

		var Menu = Bmob.Object.extend('menu');
		var menu = new Menu();
		var relation = books.relation('ids');

		menu.id = 'a331ded433';
		relation.add(menu);
		
		var currentOrderJson = cart.getJsonNames();
		for( var i = 0; i < __Array.length; i++){
			var Order = Bmob.Object.extend('order');
			var Order = new Order();
			Order.set("username", name);
			Order.set("hotel", __Array[i].hotel);
			Order.set("dishes", __Array[i].store);
			Order.set("bookday", getDay());
			
			Order.save(null, {
				success: function(object) {
				// The object was retrieved successfully.
					console.log(object);
				},
				error: function(object, error) {
					alert("query object fail");
				}
			})
		}
		
		books.save(null, {
			success: function(object) {
				var query = new Bmob.Query(Books);

				query.include('ids');
				query.equalTo('bookday', getDay());

				query.find({
					success: function(rows){
						console.log(rows);
					}
				});

				Modal.success({
					title: '订饭成功',
					content: '耐心等待美食吧！！！'
				});

				cart.clear();
			},
			error: function(object, error) {
				message.error('没订上，再试一次');
				console.log(error);
			}
		});

		localStorage.setItem('name.cart', name);
		
	}
	
	submitOrder() {
		const cart = this;
		
		if (this.state.submiting) return;
	
		var name = this.getUserName();

		if (!name) {
			message.warn("留下大名！");
			this.refs.inputname.focus();
			return false;
		} 
		
		if ( this.state.money > 26 ){
			message.error("每单限26元~");
			return false;
		}
		
		
		$.get('/timer', function(data) {
		
			if( data.time > 0){
				cart.OrderNum(function (res){
					var item, i, j;
					var currentOrderJson = cart.getJsonNames()

					for( item in currentOrderJson){
						for( i in currentOrderJson[item]){
							
							if( res != '' && typeof res[item] != 'undefined' && typeof res[item][i] != 'undefined' ){
								
								var itemNum = res[item][i] + currentOrderJson[item][i];
								
								if( itemNum > 3 ){
									message.error("每种菜品大家只能点3份哦~");
									return false;
								}
							}else{
								if( currentOrderJson[item][i] > 3 ){
									message.error("每种菜品大家只能点3份哦~");
									return false;
								}
							}
						}
					}

					cart._submitOrder()
				});				
			}else{
				message.error("已经到时间了呢~朋友！！！");
			}
		})
	}
	render() {
		let ctx = this;
		let items = this.props.dishes;
		let empty = this.state.total ? false : true;

		let text = null;

		let columns = [{
			title: '名称',
			dataIndex: 'name',
			key: 'name'
		}, {
			title: '单价',
			dataIndex: 'price',
			key: 'price'
		}, {
			title: '数量',
			dataIndex: 'total',
			key: 'total'
		}, {
			title: '操作',
			dataIndex: 'opt',
			key: 'opt',
			render: function(text, record) {
				return <span onClick={ctx.reduce.bind(ctx, record)} style={{cursor: 'pointer',fontSize: '14px'}}>
						<Icon type="minus-circle-o" />
					</span>
			}
		}];

		let data = this.state.dishes;

		if (empty) {
			text = <span>美食盒是空的</span>;
		} else {
			text = <span>总计：{this.state.money}&yen;</span>;
		}

		let username = localStorage.getItem('name.cart') || '';

		const rowKey = function(record, index) {
			return index;
		}

		return (
			<div className="cart">
				<div className="cart-bd" style={{display: this.state.dishes.length ? '' : 'none'}}>
					<div className="cart-name-ipt" style={{padding: '8px'}}>
						<input type="text" placeholder="请输入您的姓名" ref="inputname" defaultValue={username} className="ant-input"/>
					</div>

					<Table
						rowKey={rowKey}
						columns={columns}
						dataSource={this.state.dishes}
						pagination={false}
					/>
				</div>
				<Row className="cart-ft">
					<Col span="12">
						<Badge count={this.state.total}>
						<span className={empty ? "cart-icon" : "cart-icon on"}>
							<Icon type="shopping-cart" />
						</span>
						</Badge>
						{text}
					</Col>
					<Col span="12" className="cart-submit" style={{display: empty? 'none': ''}}>
						<a href="javascript:;" onClick={this.submitOrder.bind(this)}>选好了</a>
					</Col>
				</Row>
			</div>
		)
	}
}
Cart.defaultProps = {
	dishes: []
}

class HistoryList extends Component {
	render() {
		return (
			<div className="history-food">
				<h2>
				<Link to="list" style={{float: 'right', fontSize: '14px'}}>已定餐列表</Link>
				尝过的美食
				</h2>
				<div>
				<Timeline pending>
					<Timeline.Item>小鸡炖蘑菇 10&yen;</Timeline.Item>
					<Timeline.Item>天王盖地虎 20&yen;</Timeline.Item>
					<Timeline.Item>拖沓李天王 30&yen;</Timeline.Item>
					<Timeline.Item></Timeline.Item>
				</Timeline>
				</div>
			</div>
		)
	}
}

class FoodItem extends Component {
	constructor(props) {
		super(props);
		this.state = {};
	}
	render() {
		var row = this.props.item,
			img = row.img;

		if(img){
			img = <img src={img} />
		}else{
			img = '';
		}
		return (
			<li>
				<div className="img">{img}</div>
				<feature>
					<span>{row.name}</span>
					<span className="price">
						<b>{row.price}</b>
						<i>&yen;</i>
					</span>
					<FoodItemAdd item={this.props.item}></FoodItemAdd>
				</feature>
			</li>
		)
	}
}
class Index extends Component {
	constructor(props) {
		super(props);
		this.state = {
			selected: [],
			total: 0,
			seconds: 0,
			loading: true
		};

		this.getTime();
	}
	getTime() {
		var ctx = this;

		$.get('/timer', function(data) {
			var day = +data.time / 1000;

			ctx.setState({
				seconds: day,
				loading: false,
			})
		})
	}
	render() {
		if (this.state.loading) {
			return (
				<div style={{padding: '20em 0', textAlign: 'center'}}>
					<Spin size="large"/>
				</div>
			)
		}

		return (
			<div>
				<IndexBanner seconds={this.state.seconds}></IndexBanner>
				<Row>
					<Col span="20" offset="2">
						<Row>
							<Col span="17" className="main" style={{paddingRight: '40px'}}>
								
								<MenuList seconds={this.state.seconds}/>
							</Col>
							<Col span="6" offset="1" className="aside">
								<HistoryList />
								<Cart dishes={this.state.selected} />
							</Col>
						</Row>
					</Col>
				</Row>
			</div>

		)
	}
}

export {
	Index
}
